package com.github.bitsapling.sapling.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.bitsapling.sapling.mapper.InvitationCodeMapper;
import com.github.bitsapling.sapling.entity.InvitationCode;
import com.github.bitsapling.sapling.service.InvitationService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@Service
public class InvitationServiceImpl implements InvitationService {
    @Resource
    private InvitationCodeMapper invitationCodeMapper;

    @Override
    public List<String> generateInvitationCodes(InvitationCode invitationDetail, int count) {
        List<String> invitationCodes = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            // 使用 UUID 生成唯一邀请码
            String code = UUID.randomUUID().toString();
            invitationCodes.add(code);
            if(invitationDetail.getId() != null) {
                invitationDetail.setId(null);
            }
            invitationDetail.setCode(code);
            // 保存邀请码到数据库
            invitationCodeMapper.insert(invitationDetail);
        }
        return invitationCodes;
    }

    @Override
    public boolean validateInvitationCode(String invitationCode) {
        // 查询未使用的邀请码
        InvitationCode invitation = invitationCodeMapper.selectOne(
                new QueryWrapper<InvitationCode>()
                        .eq("code", invitationCode)
                        .isNull("used_by")
                        .gt("expires_time", LocalDateTime.now())
        );
        return invitation != null;
    }

    @Override
    public void markInvitationCodeUsed(String invitationCode, String userName) {
        InvitationCode invitation = new InvitationCode();
        invitation.setUsedBy(userName);
        // 更新邀请码为已使用状态
        invitationCodeMapper.update(invitation,
                new QueryWrapper<InvitationCode>().eq("code", invitationCode)
        );
    }

    @Override
    public List<String> showInvitationUnused() {
        // 查询所有未使用且未过期的邀请码记录
        List<InvitationCode> invitations = invitationCodeMapper.selectList(
                new QueryWrapper<InvitationCode>()
                        .isNull("used_by")
                        .gt("expires_time", LocalDateTime.now())
        );

        // 提取所有邀请码的code字段
        List<String> invitationCodes = new ArrayList<>();
        if (invitations != null && !invitations.isEmpty()) {
            for (InvitationCode inv : invitations) {
                invitationCodes.add(inv.getCode());
            }
        }
        return invitationCodes;
    }
}
